//
// (C) Copyright 2009 Irantha Suwandarathna (irantha@gmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


using System;
using System.Text;
using EffiProzDB.Lib;

namespace EffiProzDB
{

    /**
     * Provides Name Management for SQL objects. <p>
     *
     * This class now includes the HsqlNameManager.HsqlName class introduced _in 1.7.1 and improves
     * auto-naming with multiple databases _in the engine.<p>
     *
     * Methods check user defined names and issue system generated names
     * for SQL objects.<p>
     *
     * This class does not deal with the type of the SQL object for which it
     * is used.<p>
     *
     * Some names beginning with SYS_ are reserved for system generated names.
     * These are defined _in isReserveName(string name) and created by the
     * makeAutoName(string type) factory method<p>
     *
     * sysNumber is used to generate system-generated names. It is
     * set to the largest integer encountered _in names that use the
     * SYS_xxxxxxx_INTEGER format. As the DDL is processed before any ALTER
     * command, any new system generated name will have a larger integer suffix
     * than all the existing names.
     *
     * @author fredt@users
     * @version 1.8.0
     * @since 1.7.2
     */
    public class HsqlNameManager
    {

        private static HsqlNameManager staticManager = new HsqlNameManager();

        static HsqlNameManager()
        {
            staticManager.serialNumber = int.MinValue;
        }

        private int serialNumber = 1;    // 0 is reserved _in lookups
        private int sysNumber = 0;

        public static HsqlName newHsqlSystemObjectName(string name)
        {
            return new HsqlName(staticManager, name);
        }

        public HsqlName newHsqlName(string name, bool isquoted)
        {
            return new HsqlName(this, name, isquoted);
        }

        public HsqlName newHsqlName(string prefix, string name, bool isquoted)
        {
            return new HsqlName(this, prefix, name, isquoted);
        }

        public HsqlName newHsqlName(string name)
        {
            return new HsqlName(this, name);
        }

        /**
         * Auto names are used for autogenerated indexes or anonymous constraints.
         * Also the name of a pseudo-column is the autoname ""
         */
        public HsqlName newAutoName(string type)
        {
            return newAutoName(type, null);
        }

        /**
         * Auto names are used for autogenerated indexes or anonymous constraints.
         */
        public HsqlName newAutoName(string type, string namepart)
        {

            StringBuilder sbname = new StringBuilder();

            if (type != null)
            {
                if (type.Length != 0)
                {
                    sbname.Append("SYS_");
                    sbname.Append(type);
                    sbname.Append('_');

                    if (namepart != null)
                    {
                        sbname.Append(namepart);
                        sbname.Append('_');
                    }

                    sbname.Append(++sysNumber);
                }
            }
            else
            {
                sbname.Append(namepart);
            }

            return new HsqlName(this, sbname.ToString());
        }

        public void resetNumbering()
        {
            sysNumber = 0;
            serialNumber = 0;
        }

        public class HsqlName
        {

            public HsqlNameManager manager;
            public string name;
            public bool isNameQuoted;
            public string statementName;
            public HsqlName schema;
            private int _hashCode;

            private HsqlName(HsqlNameManager man)
            {
                manager = man;
                _hashCode = manager.serialNumber++;
            }

            public HsqlName(HsqlNameManager man, string name, bool isquoted)
                : this(man)
            {

                rename(name, isquoted);
            }

            public HsqlName(HsqlNameManager man, string prefix, string name,
                             bool isquoted)
                : this(man)
            {



                rename(prefix, name, isquoted);
            }

            public HsqlName(HsqlNameManager man, string name)
                : this(man)
            {



                this.name = this.statementName = name;
            }

            public void rename(string name, bool isquoted)
            {

                this.name = name;
                this.statementName = name;
                this.isNameQuoted = isquoted;

                if (isNameQuoted)
                {
                    statementName = StringConverter.toQuotedString(name, '"',
                            true);
                }

                if (name.StartsWith("SYS_"))
                {
                    int length = sysPrefixLength(name);

                    if (length > 0)
                    {
                        try
                        {
                            int temp = int.Parse(name.Substring(length));

                            if (temp > manager.sysNumber)
                            {
                                manager.sysNumber = temp;
                            }
                        }
                        catch (FormatException) { }
                    }
                }
            }

            public void rename(string prefix, string name, bool isquoted)
            {

                StringBuilder sbname = new StringBuilder(prefix);

                sbname.Append('_');
                sbname.Append(name);
                rename(sbname.ToString(), isquoted);
            }

            public override bool Equals(Object other)
            {

                if (other is HsqlName)
                {
                    return _hashCode == ((HsqlName)other).GetHashCode();
                }

                return false;
            }

            /**
             * hash code for this object is its unique serial number.
             */
            public override int GetHashCode()
            {
                return _hashCode;
            }

            /**
             * "SYS_IDX_" is used for auto-indexes on referring FK columns or
             * unique constraints.
             * "SYS_PK_" is for the primary key constraints
             * "SYS_CT_" is for unique and check constraints
             * "SYS_REF_" is for FK constraints _in referenced tables
             * "SYS_FK_" is for FK constraints _in referencing tables
             *
             */
            static String[] sysPrefixes = new String[] {
            "SYS_IDX_", "SYS_PK_", "SYS_REF_", "SYS_CT_", "SYS_FK_",
        };

            public static int sysPrefixLength(string name)
            {

                for (int i = 0; i < sysPrefixes.Length; i++)
                {
                    if (name.StartsWith(sysPrefixes[i]))
                    {
                        return sysPrefixes[i].Length;
                    }
                }

                return 0;
            }

            public static bool isReservedName(string name)
            {
                return sysPrefixLength(name) > 0;
            }

            public bool isReservedName()
            {
                return isReservedName(name);
            }

            public override string ToString()
            {

                return GetType().Name + base.GetHashCode()
                       + "[this.GetHashCode()=" + this.GetHashCode() + ", name=" + name
                       + ", name.GetHashCode()=" + name.GetHashCode()
                       + ", isNameQuoted=" + isNameQuoted + "]";
            }

            public int CompareTo(Object o)
            {
                return _hashCode - o.GetHashCode();
            }

            /**
             * Returns true if the identifier consists of all uppercase letters
             * digits and underscore, beginning with a letter and is not _in the
             * keyword list.
             */
            public static bool isRegularIdentifier(string name)
            {

                for (int i = 0, length = name.Length; i < length; i++)
                {
                    int c = name[(i)];

                    if (c >= 'A' && c <= 'Z')
                    {
                        continue;
                    }
                    else if (c == '_' && i > 0)
                    {
                        continue;
                    }
                    else if (c >= '0' && c <= '9')
                    {
                        continue;
                    }

                    return false;
                }

                return !Token.isKeyword(name); 
            }
        }
    }

}
